class_name Player
extends CharacterBody2D

signal collectItem

@onready var ani=$AnimatedSprite2D
@onready var mark=$Marker2D
@onready var arrowMode=preload('res://武器/弓箭.tscn')
@export var bag:Bag

var speed:=100
var state

# 装备状态
var arrowEquiped=false
# 射击许可
var canShot:=true
# 朝向
var dire='下'


func _physics_process(_delta: float) -> void:
	move()
	attack()
	changeEquiped()

# 状态动画
func animation(dir):
	if !canShot:return
	if arrowEquiped:
		var arrowDir=(get_global_mouse_position()-position).normalized()
		if arrowDir.y < -0.5:
			dire = '上'
		if arrowDir.x > 0.5:
			dire = '右'
		if arrowDir.y > 0.5:
			dire = '下'
		if arrowDir.x < -0.5:
			dire = '左'
		if arrowDir.x > 0.5 and arrowDir.y < -0.5:
			dire = '右上'
		if arrowDir.x > 0.5 and arrowDir.y > 0.5:
			dire = '右下'
		if arrowDir.x < -0.5 and arrowDir.y < -0.5:
			dire = '左上'
		if arrowDir.x < -0.5 and arrowDir.y > 0.5:
			dire = '左下'
		ani.play(dire)
		return
	match state:
		'空闲':
			ani.play(state)
		'行':
			if dir.y==-1:
				dire='上'
			if dir.x==1:
				dire='右'
			if dir.y==1:
				dire='下'
			if dir.x==-1:
				dire='左'

			if dir.x>0.5 and dir.y<-0.5:
				dire='右上'
			if dir.x>0.5 and dir.y>0.5:
				dire='右下'
			
			if dir.x<-0.5 and dir.y<-0.5:
				dire='左上'
			if dir.x<-0.5 and dir.y>0.5:
				dire='左下'
			ani.play(dire+'行')

#  移动
func move():
	var direction=Input.get_vector('左','右','上','下')
	if direction.x==0 and direction.y==0:
		state='空闲'
	elif direction.x!=0 or direction.y!=0:
		state='行'

	velocity=direction*speed
	move_and_slide()
	animation(direction)

# 收集
func collect(item:Item):
	emit_signal('collectItem',item.name)
	bag.add(item)

# 攻击
func attack():
	# 弓箭朝向鼠标
	var mousePos=get_global_mouse_position()
	mark.look_at(mousePos)
	if Input.is_action_just_pressed('攻击') and canShot and arrowEquiped:
		canShot=false
		ani.play(dire+'攻击')
		var arrow=arrowMode.instantiate()
		arrow.rotation=mark.rotation
		arrow.global_position=global_position
		await  get_tree().create_timer(0.1).timeout
		add_child(arrow)
		await  get_tree().create_timer(0.25).timeout
		canShot=true

# 切换攻击
func changeEquiped():
	if Input.is_action_just_pressed('切换射击'):arrowEquiped=!arrowEquiped



